package com.xiaodu.rest.config;

import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author: dutianjie
 * @date: 2021/4/14
 * @version: v1.0.0
 * @description: 描述
 **/
@Slf4j
public class LogClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        Stopwatch stopwatch = Stopwatch.createStarted();
        String method = request.getMethodValue();
        String uri = request.getURI().toString();
        ClientHttpResponse response = execution.execute(request, body);
        log.warn("\n【\t{}  [{}] \n body: {} \n 请求耗时：{}ms】", uri, method, new String(body, StandardCharsets.UTF_8), stopwatch.elapsed(TimeUnit.MILLISECONDS));
        return response;
    }
}
